package net.jltec.view.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.jltec.config.AppConfig;
import net.jltec.utils.CallBackMethod;
import net.jltec.utils.ProcessMethod;
import net.jltec.utils.WebUtils;
import net.jltec.view.R;
import net.jltec.view.adapter.TaskListAdapter;
import net.jltec.view.base.JltecBaseUI;
import net.jltec.view.bean.Model;
import net.jltec.view.bean.Task;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

@SuppressWarnings({"unchecked","rawtypes"})
public class JltecTaskUI extends JltecBaseUI implements OnItemClickListener,OnScrollListener,OnClickListener {

	
	private TextView titleTextView;
	private Model model;
	
	private ListView taskListView;
	private TaskListAdapter taskListAdapter;
	private TextView pageText;
	
	private int visibleLastIndex = 0; // 最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private int datasize = 1; // 模拟数据集的条数
	private int row=10;
	private int pageIndex=1;
	
	private View loadMoreView;
	private Button loadMoreButton;
	
	private PopupWindow mPopup;
	private LayoutInflater mInflater;
	
	private ImageView helpImageView ;
	
	//审批
	public static final int OPT_SP=1;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // 声明使用自定义标题
		setContentView(R.layout.mani_task);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.main_title);// 自定义布局赋值

		initParams();
		initData();
	}
	 
	 
	 private void initParams(){
		loadMoreView = getLayoutInflater().inflate(R.layout.main_task_load_more, null);
		//loadMoreView.setVisibility(View.GONE);
		loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
		loadMoreButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				loadMoreButton.setText("正在加载中..."); // 设置按钮文字
				loadMoreData();
			}
		});
		
		
		 
		 
		 taskListView = (ListView) findViewById(R.id.taskListView);
		 taskListView.addFooterView(loadMoreView);    //设置列表底部视图  
		 taskListView.setOnScrollListener(this);  
		 taskListView.setOnItemClickListener(this);
		  
		 
		taskListAdapter = new TaskListAdapter(JltecTaskUI.this, new ArrayList<Task>());
		taskListView.setAdapter(taskListAdapter);
		

		
		titleTextView = (TextView) findViewById(R.id.main_title_id);
		 
		 
		 model = (Model) getIntent().getSerializableExtra("model");
		 if(model!=null){
			 titleTextView.setText(model.name);
		 }
		 
		 helpImageView = (ImageView) findViewById(R.id.title_help_btn);
		 helpImageView.setOnClickListener(this);
	 }
	 
	/**
	 * 加载更多数据
	 */
	private void loadMoreData() {
		initData();
	}
	 
	 
	 
	 private void initData(){
		 asynMethod(new ProcessMethod() {
			@Override
			public Object execute() {
				Map params = createOAuthUserMap();
				params.put("pageIndex", (pageIndex++)+"");
				params.put("row", row+"");
				String result =  WebUtils.doGet(AppConfig.GET_FLOW_TASK,params);
				List<Map> list = JSON.parseArray(result, Map.class);
				return list;
			}
		}, new CallBackMethod() {
			@Override
			public void execute(Object result) {
				List<Task> tasks = new ArrayList<Task>();
				List list =  (List) result;
				
				int totalCount = 0;
				for(int i=0;i<list.size();i++){
					Map m = (Map) list.get(i);
					
					Task task = new Task();
					task.wiid = convert( m.get("wiid"),Integer.class);
					task.winid =convert(m.get("winid"),Integer.class);
					task.note = convert(m.get("note"),String.class);
					task.createdt = convert(m.get("createdt"),String.class);
					task.nodename = convert(m.get("nodename"),String.class);
					
					tasks.add(task);
					
					totalCount = convert( m.get("rowcnt"),Integer.class);
					datasize = totalCount;
					taskListAdapter.addTask(task);
				}
				loadMoreButton.setVisibility(View.VISIBLE);
				loadMoreButton.setText("共有"+(datasize-1)+"条,查看更多..."); // 恢复按钮文字
				taskListAdapter.notifyDataSetChanged();
			}
		});
	 }
	 
	 
	 


	 Map currMap ;
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		currPosition = position;
		if(parent==taskListView){
			Task task = taskListAdapter.getItem(position);
			showTaskDetial(task,view);
		}
	}
	
	
	int currPosition;
	private void showTaskDetial(final Task task,final View view){
		 Intent i = new Intent(this,JltecTaskDetailUI.class);
		 i.putExtra("model", task);
		 startActivityForResult(i, OPT_SP);
		 //showPopupMenu(task,view);
	}
	private RadioGroup group ; //点选按钮组
	private void showPopupMenu(Task task, View view) {
		 if(this.mPopup==null){
			 LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			 View v = lay.inflate(R.layout.main_task_detail, null);
			 //v.setBackgroundResource(R.drawable.rounded_corners_pop); 
			 
			 this.mPopup = new PopupWindow(v);
			 this.mPopup.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_corners_pop));

		 } 
		 
		 this.mPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
		 this.mPopup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
		 
		 group =(RadioGroup) this.mPopup.getContentView().findViewById(R.id.task_detail_radio_group);
		 group.removeAllViews();

		// 添加单选按钮
		for (int i = 0; i <2; i++) {
			RadioButton radio = new RadioButton(this);
			radio.setText("radio" + i);
			radio.setId(i);
			radio.setTextColor(Color.BLACK);
			
			group.addView(radio);
		}
		 
		this.mPopup.setFocusable(true);
		//this.mPopup.setBackgroundDrawable(new BitmapDrawable());
		this.mPopup.setFocusable(true);
		this.mPopup.setTouchable(true);
		this.mPopup.setOutsideTouchable(true);
		//this.mPopup.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		this.mPopup.showAtLocation(view, Gravity.CENTER_VERTICAL, 0, 0);
	}


	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = taskListAdapter.getCount()-1;  //数据集最后一项的索引    
        int lastIndex = itemsLastIndex + 1;  
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE  
                && visibleLastIndex == lastIndex) {  
            // 如果是自动加载,可以在这里放置异步加载数据的代码  
        }  
	}


	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		 this.visibleItemCount = visibleItemCount;  
	        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  
	          
//	        Log.e("========================= ","========================");  
//	        Log.e("firstVisibleItem = ",firstVisibleItem+"");  
//	        Log.e("visibleItemCount = ",visibleItemCount+"");  
//	        Log.e("totalItemCount = ",totalItemCount+"");
//	        Log.e("datasize = ",datasize+"");  
//	        Log.e("========================= ","========================");  
	          
	        //如果所有的记录选项等于数据集的条数，则移除列表底部视图  
	        if(totalItemCount == datasize+1){  
	        	removeLoadMoreView();
	        }  
	}
	
	private void removeLoadMoreView(){
		 sendMainThreadMethod(new CallBackMethod() {
				@Override
				public void execute(Object result) {
					//因为在onScroll方法中删除后，listview 变得无法单击了,所以放在这里
					taskListView.removeFooterView(loadMoreView);  
				}
			});
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			switch (resultCode) {
			case OPT_SP:
				 HashMap params = (HashMap) data.getSerializableExtra("params");
				 updateTask();
				 showToast("操作成功!");
				break;
			}
		}
	}
	
	private void updateTask(){
		asynMethod(new ProcessMethod() {
			@Override
			public Object execute() {
				Task task = taskListAdapter.getItem(currPosition);
				Map params =createOAuthUserMap();
				params.put("wiid",task.wiid);
				String json = WebUtils.doPost(AppConfig.GET_FLOW_BY_WIID, params);
				return json;
			}
		}, new CallBackMethod() {
			@Override
			public void execute(Object result) {
				if(result==null || "null".equals(result)){
					taskListAdapter.removeTask(currPosition);
				}else{
					Task task = new Task();
					Map params = JSON.parseObject(result.toString(), Map.class);
					task.createdt=convert(params.get("createdt"),String.class);
					task.wiid=convert(params.get("wiid"),Integer.class);
					task.winid=convert( params.get("winid"),Integer.class);
					task.nodename=convert( params.get("nodename"),String.class);
					task.note=convert( params.get("note"),String.class);
					taskListAdapter.setTask(task, currPosition);
				}
				
				System.out.println("sp-->"+result);
			}
		});
	}


	@Override
	public void onClick(View v) {
		if(v==helpImageView){
			this.mInflater = LayoutInflater.from(this);
			View view = this.mInflater.inflate(R.layout.popup_menu, null);
			showHelpPopupMenu(view, v);
		}
	}
}

